﻿using System;
using System.Text;

namespace Tw.Trains.Domain
{
    public class TripNode : Station
    {
        public TripNode(string name) : base(name)
        {
        }
        public TripNode Next { get; set; }
        /// <summary> 节点属性 </summary>
        public TripAttribute Attribute { get; set; }

        /// <summary> 添加节点 </summary>
        /// <param name="node"></param>
        public void Append(TripNode node)
        {
            if (node == null)
                return;
            var next = this;
            while (next != null)
            {
                if (next.Next == null)
                {
                    next.Next = node;
                    //重置子节点整体线路属性
                    _tripAttribute = null;
                    break;
                }
                next = next.Next;
            }
        }

        private TripAttribute _tripAttribute;

        /// <summary> 子节点整体线路属性 </summary>
        public TripAttribute TripAttribute()
        {
            if (_tripAttribute != null)
                return _tripAttribute;
            var attr = new TripAttribute(0) { Stops = 0 };
            var node = Next;
            while (node != null)
            {
                if (node.Attribute == null)
                {
                    throw new Exception("Property Attribute is null");
                }
                attr.Distance += node.Attribute.Distance;
                attr.Stops += 1;
                node = node.Next;
            }
            return _tripAttribute = attr;
        }

        public override string ToString()
        {
            var sb = new StringBuilder(Name);
            var node = Next;
            while (node != null)
            {
                sb.AppendFormat("-{0}", node.Name);
                node = node.Next;
            }
            return sb.ToString();
        }

        /// <summary> 深度克隆 </summary>
        public TripNode Clone()
        {
            var clone = new TripNode(Name) { Attribute = Attribute };
            var next = Next;
            while (next != null)
            {
                clone.Append(new TripNode(next.Name) { Attribute = next.Attribute });
                next = next.Next;
            }
            return clone;
        }
    }
}
